<template>
  <div class="comment-form-container">
    <el-card class="comment-card">
      <template #header>
        <div class="card-header">
          <h3>发表评论</h3>
        </div>
      </template>
      
      <div v-if="isLoggedIn" class="form-content">
        <el-form 
          ref="commentForm" 
          :model="comment" 
          :rules="rules" 
          label-width="80px"
        >
          <el-form-item label="评论内容" prop="content">
            <el-input
              v-model="comment.content"
              type="textarea"
              :rows="4"
              placeholder="请输入评论内容..."
              style="width: 100%"
            />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="submitComment">提交评论</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <div v-else class="login-prompt">
        <p>请登录后发表评论</p>
        <el-button type="primary" @click="goToLogin">登录</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/userStore'
import { useCommentStore } from '@/stores/commentStore'

// 接收文章ID
const props = defineProps({
  articleId: {
    type: String,
    required: true
  }
})

const router = useRouter()
const userStore = useUserStore()
const commentStore = useCommentStore()
const commentForm = ref<HTMLFormElement | null>(null)

// 计算是否已登录
const isLoggedIn = computed(() => userStore.isLoggedIn)

// 评论表单数据
const comment = reactive({
  articleId: props.articleId,
  content: '',
  author: userStore.user?.username || ''
})

// 表单验证规则
const rules = {
  content: [{ required: true, message: '请输入评论内容', trigger: 'blur' }]
}

// 提交评论
const submitComment = async () => {
  if (!commentForm.value) return
  
  await commentForm.value.validate(async (valid) => {
    if (valid) {
      try {
        await commentStore.addComment(comment)
        comment.content = ''
        ElMessage.success('评论发表成功')
        
        // 触发父组件刷新评论列表
        emit('commentAdded')
      } catch (error: any) {
        ElMessage.error(error.response?.data?.message || '评论发表失败')
      }
    } else {
      console.log('表单验证失败')
      return false
    }
  })
}

// 前往登录页面
const goToLogin = () => {
  router.push('/login')
}
</script>

<style scoped>
.comment-form-container {
  margin-bottom: 30px;
}

.comment-card {
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.form-content {
  padding: 10px 0;
}

.login-prompt {
  padding: 20px 0;
  text-align: center;
}

.login-prompt p {
  margin-bottom: 15px;
  color: #909399;
}
</style>